//
//  Product_Show_ViewController.m
//  Pacific_Computer
//
//  Created by dlios on 14-12-17.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "Product_Show_ViewController.h"
#import "ShowCell.h"
#import "UIImageView+WebCache.h"
#import "Product_Details_ViewController.h"
#import "UIScrollView+Extension.h"
#import "UIScrollView+MJRefresh.h"
#import "NetHandler.h"

@interface Product_Show_ViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,retain) UITableView *tableView;
@property (nonatomic,retain) NSMutableArray *arr;
@property (nonatomic,assign) NSInteger num;


@end

@implementation Product_Show_ViewController

- (void)dealloc
{
    [_tableView release];
    [_arr release];
    [_pro release];
    [_urlStr release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        //[self hanldeData];
        self.num = 2;
    }
    return self;
}


- (void)hanldeData
{
    NSLog(@"重复");
    NSString *path = [NSString stringWithFormat:@"http://mrobot.pconline.com.cn/v3/product/types/%@?brandId=%@&orderId=1&pageNo=1", self.urlStr, self.pro.id];
    path = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:path];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
    request.HTTPMethod = @"GET";
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        NSError *error = nil;
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
        NSArray *arr = [result objectForKey:@"data"];
        
        self.arr = [NSMutableArray array];
        for (NSDictionary *dic in arr) {
            Parameter *par = [[Parameter alloc] initWithDictionary:dic];
            [self.arr addObject:par];
            [par release];
        }
        [self.tableView reloadData];
        
        
    }];
    
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = self.pro.name;

    [self hanldeData];
    
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.rowHeight = self.tableView.bounds.size.height * 13.49 / 100;
    [self.view addSubview:self.tableView];
    [_tableView release];

    [self setupRefresh];
    

    
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arr.count;
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *str = @"parone";
    ShowCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (!cell) {
        cell = [[[ShowCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:str] autorelease];
    }
    Parameter *par = [self.arr objectAtIndex:indexPath.row];
    
    
    cell.titleLabel.text = par.shortName;
    NSString *priStr = [par.price stringValue];
    NSString *price;
    if ([priStr isEqualToString:@"-1"]) {
        price = @"价格：无参考价格";
    }else{
        price = [NSString stringWithFormat:@"￥:%@",par.price];
    }
    cell.PriceLabel.text = price;

    UIImage *image = [UIImage imageNamed:@"right.png"];
    cell.rightImage.image = image;
    
    NSString *stb = par.idxPic;
    stb = [stb stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:stb];
    [cell.productImage setImageWithURL:url];
    

    if (par.items.count >= 2 ) {
        NSString *sizeTwo = [NSString stringWithFormat:@"%@:%@",[par.items objectAtIndex:0], [par.items objectAtIndex:1]];
        cell.SizeLabel.text =sizeTwo;
    }
    
    
    
    
    if (par.items.count >= 4 ) {
        NSString *cpuTwo = [NSString stringWithFormat:@"%@:%@",[par.items objectAtIndex:2], [par.items objectAtIndex:3]];
        cell.CPULabel.text = cpuTwo;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    Product_Details_ViewController *detail = [[Product_Details_ViewController alloc] init];
    detail.para = [self.arr objectAtIndex:indexPath.row];
    
    [self.navigationController pushViewController:detail animated:YES];
    
}


- (void)setupRefresh
{
    
    //    NSLog(@"进入了setupRefresh");
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
}

- (void)headerRereshing
{
    
    //1. 在这调用请求网络数据方法（刷新数据）
    [self hanldeData];
    self.num = 1;
    
    
    //2. 2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.tableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableView headerEndRefreshing];
    });
}


//   进入加载状态,上拉刷新
- (void)footerRereshing
{


    NSString *str = [NSString stringWithFormat:@"%ld",(long)self.num];
    
    NSString *path = [NSString stringWithFormat:@"http://mrobot.pconline.com.cn/v3/product/types/%@?brandId=%@&orderId=1&pageNo=%@", self.urlStr, self.pro.id,str];
    
    [NetHandler getDataWithUrl:path completion:^(NSData *data) {
        self.num ++;
        
        NSError *error = nil;
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
        NSArray *arr = [result objectForKey:@"data"];
        
        for (NSDictionary *dic in arr) {
            Parameter *par = [[Parameter alloc] initWithDictionary:dic];
            [self.arr addObject:par];
            [par release];
        
        }
    }];
    
    
    
    
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableView reloadData];
        [self.tableView footerEndRefreshing];
    });
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
